/**
 *  TODO 1 导入模块
 *  * express
 *  * cors 解决跨域
 *  * morgan 日志
 *  * router 路由模块
 *
 */
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');

const router = require('./router/user');
const userinfo = require('./router/userinfo');
const art = require('./router/art');
const articles = require('./router/articles');
const upload = require('./router/upload');

const joi = require('joi');
const config = require('./config');
const expressJWT = require('express-jwt');

const port = 3006;

const app = express();

/**
 *  TODO 2 中间件
 *  * 解决跨域 解析数据 输出日志 路由
 */
app.use(express.json());
app.use(cors());
app.use('/uploads', express.static('./uploads'));
app.use(express.urlencoded({ extended: false }));
app.use(morgan('dev'));
app.use(
  expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] })
);
app.use('/api', router);
app.use('/my', userinfo);
app.use('/my/article', art);
app.use('/my/article', articles);
app.use('/my', upload);

//  TODO 3 错误级别中间件
app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError)
    return res.send({
      success: false,
      message: err.message,
    });
  if (err.name === 'UnauthorizedError')
    return res.send({
      success: false,
      message: '身份认证失败！',
    });
  res.send({
    success: false,
    message: err,
  });
  next();
});
//  TODO 4 启动服务
app.listen(port, () => {
  console.log(`running at http://127.0.0.1:${port}`);
});
